package com.itheima.d7_tcp4;

import java.io.*;
import java.net.Socket;
import java.util.List;

public class ServerReaderThread implements Runnable{
    private Socket socket;

    public ServerReaderThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedReader br = null;
        // 3、从socket通信管道中得到一个字节输入流。
        try {
            InputStream inputStream =  socket.getInputStream();
            //转换流，将字节流转换为字符流
            InputStreamReader isr = new InputStreamReader(inputStream);

            // 4、把原始的字节输入流包装成高效的输入流
            br = new BufferedReader(isr);
            while (true) {
                // 5、使用数据输入流读取客户端发送过来的消息
                String s = br.readLine();

                if(s == null){
                    System.out.println(socket.getInetAddress().getHostName() + "断开连接----------------");
                    Server.sockets.remove(socket);
                    break;
                }else {
                    System.out.println(socket.getInetAddress().getHostName() + " (" + socket.getInetAddress().getHostAddress() + ") " + ": " + s);
//                    System.out.println(socket.getInetAddress().getHostAddress() + ": " + s);

                    for (Socket otherSocket : Server.sockets) {
                        //判断拿到的socket是否是当前对象
                        if(otherSocket!=socket){
                            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(otherSocket.getOutputStream()));
                            writer.write(s);
                            writer.newLine();
                            writer.flush();
                        }
                    }
                }
            }

        } catch (IOException e) {
            Server.sockets.remove(socket);
            System.out.println(socket.getInetAddress().getHostName() + "断开连接----------------");
        }finally {
            try {
                if(br != null){
                    br.close();
                }
                // 6、释放资源
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
